//
//  LiveNews.m
//  ios_news
//
//  Created by Han on 14-7-7.
//  Copyright (c) 2014年 ucoder. All rights reserved.
//

#import "LiveNews.h"
#import "AFNetworking.h"

@implementation LiveNews


- (instancetype)initWithAttributes:(NSDictionary *)attributes {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    self.nid    = (NSUInteger)[[attributes valueForKeyPath:@"nid"] integerValue];
    self.title  = [attributes valueForKeyPath:@"node_title"];
    self.content = [attributes valueForKeyPath:@"node_content"];
    self.icon = [attributes valueForKeyPath:@"node_icon"];
    self.time = [attributes valueForKeyPath:@"node_created"];

    
    return self;
}

// 属性变量转码
-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeInteger:self.nid forKey:@"nid"];
    [aCoder encodeObject:self.title forKey:@"title"];
    [aCoder encodeObject:self.content forKey:@"content"];
}
// 属性变量根据关键字进行逆转码，最后返回对象
-(id)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super init]) {
        
        self.nid = [aDecoder decodeIntForKey:@"nid"];
        self.title = [aDecoder decodeObjectForKey:@"title"];
        self.content = [aDecoder decodeObjectForKey:@"content"];
        
    }
    return self;
}


+ (NSURLSessionDataTask *)getDataWithBlock:(void (^)(NSArray *posts, NSError *error))block :(NSString *) url {
    AFHTTPSessionManager *sharedClient = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
    sharedClient.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    
    return [sharedClient GET:@"" parameters:nil success:^(NSURLSessionDataTask * __unused task, id JSON) {
        
        NSArray *responseData = JSON;  // [JSON valueForKeyPath:@"data"]
        NSMutableArray *mutableNews = [NSMutableArray arrayWithCapacity:[responseData count]];
        
        //NSLog(@"%@", responseData);
        
        for (NSDictionary *attributes in responseData) {
            LiveNews *news = [[LiveNews alloc] initWithAttributes:attributes];
            [mutableNews addObject:news];
        }
        
        if (block) {
            block([NSArray arrayWithArray:mutableNews], nil);
        }
        
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        if (block) {
            block([NSArray array], error);
        }
    }];
}

@end
